<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { getCurrentInstance, h, nextTick, reactive, ref } from "vue";
import { VxeGridInstance, VxeGridProps, VxeUI } from "vxe-table";
import {
  pulperVersionGetList,
  pulperVersionPublish,
  pulperVersionAdd,
  pulperVersionDel,
  pulperVersionUpd,
  pulperVersionGetReleaseList,
  pulperVersionRelease,
  PulperVersionListProp,
  pulperFormulaGetList
} from "@/api/pulper/formula";
import { pick } from "lodash-unified";
import IssueModal from "@/components/Autata/IssueModal.vue";
import { AuModal } from "@/components/AuModal";
import { ElMessage, ElMessageBox } from "element-plus";
import { AuTable } from "@/components/AuTable";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "FormulaTeaPowderVersion"
});

const { proxy } = getCurrentInstance();
const router = useRouter();
const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formulaVersion.name",
    placeholder: "formulaVersion.namePlaceholder"
  }
  // {
  //   type: "select",
  //   key: "publishStatus",
  //   label: "formulaVersion.status",
  //   placeholder: "formulaVersion.statusPlaceholder",
  //   labelKey: "label",
  //   valueKey: "value",
  //   emptyValues: [null, undefined],
  //   options: [
  //     {
  //       value: "",
  //       label: "formulaVersion.statusAll"
  //     },
  //     {
  //       value: "0",
  //       label: "formulaVersion.statusDown"
  //     },
  //     {
  //       value: "1",
  //       label: "formulaVersion.statusUp"
  //     }
  //   ],
  //   defaultValue: ""
  // }
]);
const formPopList = ref([
  {
    type: "input",
    key: "name",
    label: "formulaVersion.name",
    placeholder: "formulaVersion.namePlaceholder",
    required: true
  },
  {
    type: "select",
    key: "copyVersion",
    label: "formulaVersion.copy",
    placeholder: "formulaVersion.copyPlaceholder",
    labelKey: "name",
    valueKey: "id",
    columns: []
  },
  {
    type: "input",
    key: "note",
    label: "table.note",
    placeholder: "formulaVersion.notePlaceholder",
    inType: "textarea"
  }
]);
const activeType = ref();
const showPopup = ref(false);

const showTreePopup = ref(false);
const versionId = ref(0);

// region 组件 ref 部分
const xGrid = ref();
const formRef = ref();
const formPopRef = ref();
// endregion

const gridOptions = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    { field: "name", title: "formulaVersion.name", align: "center" },
    { field: "note", title: "table.note", align: "center" },
    // {
    //   field: "publish_status",
    //   title: "formulaVersion.status",
    //   slots: { default: "status_default" },
    //   align: "center"
    // },
    {
      field: "updateTime",
      title: "formulaVersion.updateTime",
      align: "center",
      width: 190
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.TDELETE, ACTION_TYPE.EDIT],
  operateTools: [
    {
      key: ACTION_TYPE.VIEW,
      name: "formulaVersion.viewFormula"
    },
    // {
    //   key: ACTION_TYPE.PUTAWAY,
    //   name: "formulaVersion.putaway",
    //   hiddenHandle: (row: ObjectProps) => {
    //     return row.publishStatus === 0;
    //   }
    // },
    // {
    //   key: ACTION_TYPE.OFFSHELVE,
    //   name: "formulaVersion.offshelve",
    //   hiddenHandle: (row: ObjectProps) => {
    //     return row.publishStatus === 1;
    //   }
    // },
    {
      key: ACTION_TYPE.ISSUED,
      name: "formulaVersion.issueFormula"
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        const { size, start_page, ...rest } = params;
        const p = {
          size,
          start_page,
          filter: {
            ...rest
          }
        };

        return pulperVersionGetList(p);
      },
      param: () => formRef.value.getFormData()
    }
  }
});
// region 公共引用方法部分

const getPopVersion = () => {
  const params = {
    start_page: 1,
    size: 0
  };
  pulperVersionGetList(params).then(res => {
    // formPopList.value[2].options = res.data;
    formPopRef.value.setFormProps("copyVersion", {
      options: res.data,
      hidden: false
    });
  });
};

/**
 * 上架/下架
 * @param row {PulperVersionListProp}
 */
const handleUpOrDown = (row: PulperVersionListProp) => {
  // const msg = `是否确认${row.publishStatus === 0 ? "上架" : "下架"}物料配方${row.name}？`;

  const msg = t("formulaVersion.confirmPutaway_mat", {
    status:
      row.publishStatus === 0
        ? t("formulaVersion.offshelve")
        : t("formulaVersion.putaway"),
    name: row.name
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      publishStatus: row.publishStatus ? 0 : 1,
      ids: [row.id]
    };
    pulperVersionPublish(param).then(res => {
      if (res.code === 200) {
        VxeUI.modal.message({
          content: t("notice.operation_success"),
          status: "success"
        });
        search();
      }
    });
  });
};

// endregion

// region 组件的事件部分
const search = () => {
  xGrid.value.refresh();
};

const actionClick = ({ key, row }) => {
  activeType.value = key;
  switch (key) {
    case ACTION_TYPE.TADD:
      showPopup.value = true;
      getPopVersion();
      nextTick(() => {
        formPopRef.value.reset();
      });
      break;
    case ACTION_TYPE.EDIT:
      showPopup.value = true;
      nextTick(() => {
        formPopRef.value.setFormData(row);
        formPopRef.value.setFormProps("copyVersion", { hidden: true });
      });
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(t("formula.version.delete_confirm"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checkRows = xGrid.value.getCheckboxRecords();
          if (checkRows.length > 0) {
            const ids = checkRows.map(item => item.id);
            pulperVersionDel({ ids }).then(res => {
              if (res.code === 200) {
                VxeUI.modal.message({
                  content: t("notice.operation_success"),
                  status: "success"
                });
                xGrid.value.refresh();
              }
            });
          }
        })
        .catch(() => {});
      break;
    case ACTION_TYPE.OFFSHELVE:
    case ACTION_TYPE.PUTAWAY:
      handleUpOrDown(row);
      break;
    case ACTION_TYPE.ISSUED:
      versionId.value = row.id;
      showTreePopup.value = true;
      break;
    case ACTION_TYPE.VIEW:
      // showFormulaViewModal.value = true;
      router.push({
        name: "FormulaPulperDetail",
        query: pick(row, ["id", "name"])
      });
      break;
    default:
      break;
  }
};

const handleConfirm = async () => {
  const validate = await formPopRef.value.validate();
  if (!validate.check) return;
  let formData = formPopRef.value.getFormData();
  let api = pulperVersionAdd;
  if (activeType.value === ACTION_TYPE.TADD) {
    api = pulperVersionAdd;
    formData.publishStatus = 1;
  } else if (activeType.value === ACTION_TYPE.EDIT) {
    api = pulperVersionUpd;
    formData = pick(formData, ["id", "name", "note"]);
  }
  api(formData).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: formData.id
          ? t("formula.version.edit_success")
          : t("formula.version.add_success"),
        type: "success"
      });
      showPopup.value = false;
      xGrid.value.refresh();
    }
  });
};

const confirmPushCheck = async (data: { version: string }) => {
  const params = {
    start_page: 1,
    size: 0,
    filter: {
      versionId: data.version
    }
  };
  const res = await pulperFormulaGetList(params);
  if (!res.data.length || !res.data[0].specs?.length) {
    ElMessage({
      message: t("formulaVersion.no_mode_warning"),
      type: "warning"
    });
    return false;
  }

  const specs = res.data[0].specs;
  if (specs.length) {
    if (res.data[0].specs?.length < 4) {
      ElMessage({
        message: t("formulaVersion.mode_count_warning"),
        type: "warning"
      });
      return false;
    }

    for (const spec of specs) {
      const details = JSON.parse(spec.details);
      if (!details.times || !details.level) {
        ElMessage({
          message: t("formulaVersion.mode_detail_warning", {
            spec: spec.specName
          }),
          // message: `该版本${spec.specName}的捣汁次数和档位未填写，请点击详情补充！`,
          type: "warning"
        });
        return false;
      }
    }
  }
  return true;
};
// endregion
</script>
<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        labelWidth="60px"
        :formList="formList"
        @submit="search"
      />
    </vxe-card>

    <vxe-card
      :padding="false"
      class="mt-[16px] flex-grow overflow-hidden table-wrap"
      :border="false"
    >
      <AuTable ref="xGrid" v-bind="gridOptions" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="row.publishStatus ? 'success' : 'info'"
            >{{
              row.publishStatus
                ? t("formulaVersion.statusUp")
                : t("formulaVersion.statusDown")
            }}
          </el-tag>
        </template>
      </AuTable>
    </vxe-card>

    <AuModal
      v-model="showPopup"
      :title="
        activeType === ACTION_TYPE.TADD
          ? t('formulaVersion.addTitle')
          : t('formulaVersion.editTitle')
      "
      :width="460"
      show-zoom
      :padding="false"
      @handleConfirm="handleConfirm"
    >
      <div class="flex justify-center pt-[30px] pb-[12px] pr-[20px]">
        <AuForm
          ref="formPopRef"
          :formList="formPopList"
          :isInline="false"
          :hiddenBtn="true"
          class="!w-[400px]"
        />
      </div>
    </AuModal>

    <!--    <IssueModal v-model:showModal="showTreePopup" :versionId="versionId" />-->
    <IssueModal
      v-model="showTreePopup"
      :versionId="versionId"
      device-id-type="ATT-JU"
      :confirm-check-fn="confirmPushCheck"
      :release-fn="[pulperVersionRelease, pulperVersionGetReleaseList]"
    />
    <!--    <FormulaViewModal-->
    <!--      v-model:showModal="showFormulaViewModal"-->
    <!--      :versionId="versionId"-->
    <!--    />-->
  </div>
</template>
